extends layout

append style
  link(rel="stylesheet", href="/docs/css/inlinecpc.css")
  script(type="text/javascript" src="/docs/js/native.js")

block content
  :markdown
    ## Queries

    <script>
      _native.init("CK7DT53U",{
        targetClass: 'native-inline'
      });
    </script>

    <div class="native-inline">
      <a href="#native_link#"><span class="sponsor">Sponsor</span> #native_company# — #native_desc#</a>
    </div>

    Mongoose [models](./models.html) provide several static helper functions
    for [CRUD operations](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete).
    Each of these functions returns a
    [mongoose `Query` object](http://mongoosejs.com/docs/api.html#Query).

    - [`Model.deleteMany()`](/docs/api.html#model_Model.deleteMany)
    - [`Model.deleteOne()`](/docs/api.html#model_Model.deleteOne)
    - [`Model.find()`](/docs/api.html#model_Model.find)
    - [`Model.findById()`](/docs/api.html#model_Model.findById)
    - [`Model.findByIdAndDelete()`](/docs/api.html#model_Model.findByIdAndDelete)
    - [`Model.findByIdAndRemove()`](/docs/api.html#model_Model.findByIdAndRemove)
    - [`Model.findByIdAndUpdate()`](/docs/api.html#model_Model.findByIdAndUpdate)
    - [`Model.findOne()`](/docs/api.html#model_Model.findOne)
    - [`Model.findOneAndDelete()`](/docs/api.html#model_Model.findOneAndDelete)
    - [`Model.findOneAndRemove()`](/docs/api.html#model_Model.findOneAndRemove)
    - [`Model.findOneAndReplace()`](/docs/api.html#model_Model.findOneAndReplace)
    - [`Model.findOneAndUpdate()`](/docs/api.html#model_Model.findOneAndUpdate)
    - [`Model.replaceOne()`](/docs/api.html#model_Model.replaceOne)
    - [`Model.updateMany()`](/docs/api.html#model_Model.updateMany)
    - [`Model.updateOne()`](/docs/api.html#model_Model.updateOne)

    A mongoose query can be executed in one of two ways. First, if you
    pass in a `callback` function, Mongoose will execute the query asynchronously
    and pass the results to the `callback`.

    A query also has a `.then()` function, and thus can be used as a promise.

    <ul class="toc">
      <li><a href="#executing">Executing</a></li>
      <li><a href="#queries-are-not-promises">Queries are Not Promises</a></li>
      <li><a href="#connection-string-options">Connection String Options</a></li>
      <li><a href="#refs">References to other documents</a></li>
      <li><a href="#streaming">Streaming</a></li>
    </ul>

    ### Executing

    When executing a query with a `callback` function, you specify your query as a JSON document. The JSON document's syntax is the same as the [MongoDB shell](http://docs.mongodb.org/manual/tutorial/query-documents/).

    ```javascript
    var Person = mongoose.model('Person', yourSchema);

    // find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
    Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
      if (err) return handleError(err);
      // Prints "Space Ghost is a talk show host".
      console.log('%s %s is a %s.', person.name.first, person.name.last,
        person.occupation);
    });
    ```

    Mongoose executed the query and passed the results passed to `callback`. All callbacks in Mongoose use the pattern:
    `callback(error, result)`. If an error occurs executing the query, the `error` parameter will contain an error document, and `result`
    will be null. If the query is successful, the `error` parameter will be null, and the `result` will be populated with the results of the query.

    Anywhere a callback is passed to a query in Mongoose, the callback follows the pattern `callback(error, results)`. What `results` is depends on the operation: For `findOne()` it is a [potentially-null single document](./api.html#model_Model.findOne), `find()` a [list of documents](./api.html#model_Model.find), `count()` [the number of documents](./api.html#model_Model.count), `update()` the [number of documents affected](./api.html#model_Model.update), etc. The [API docs for Models](./api.html#model-js) provide more detail on what is passed to the callbacks.

    Now let's look at what happens when no `callback` is passed:

    ```javascript
    // find each person with a last name matching 'Ghost'
    var query = Person.findOne({ 'name.last': 'Ghost' });

    // selecting the `name` and `occupation` fields
    query.select('name occupation');

    // execute the query at a later time
    query.exec(function (err, person) {
      if (err) return handleError(err);
      // Prints "Space Ghost is a talk show host."
      console.log('%s %s is a %s.', person.name.first, person.name.last,
        person.occupation);
    });
    ```

    In the above code, the `query` variable is of type [Query](./api.html#query-js).
    A `Query` enables you to build up a query using chaining syntax, rather than specifying a JSON object.
    The below 2 examples are equivalent.

    ```javascript
    // With a JSON doc
    Person.
      find({
        occupation: /host/,
        'name.last': 'Ghost',
        age: { $gt: 17, $lt: 66 },
        likes: { $in: ['vaporizing', 'talking'] }
      }).
      limit(10).
      sort({ occupation: -1 }).
      select({ name: 1, occupation: 1 }).
      exec(callback);

    // Using query builder
    Person.
      find({ occupation: /host/ }).
      where('name.last').equals('Ghost').
      where('age').gt(17).lt(66).
      where('likes').in(['vaporizing', 'talking']).
      limit(10).
      sort('-occupation').
      select('name occupation').
      exec(callback);
    ```

    A full list of [Query helper functions can be found in the API docs](./api.html#query-js).

    <h3 id="queries-are-not-promises">
      <a href="#queries-are-not-promises">
        Queries are Not Promises
      </a>
    </h3>

    Mongoose queries are **not** promises. They have a `.then()`
    function for [co](https://www.npmjs.com/package/co) and
    [async/await](http://thecodebarbarian.com/common-async-await-design-patterns-in-node.js.html)
    as a convenience. However, unlike promises, calling a query's `.then()`
    can execute the query multiple times.

    For example, the below code will execute 3 `updateMany()` calls, one
    because of the callback, and two because `.then()` is called twice.

    ```javascript
    const q = MyModel.updateMany({}, { isDeleted: true }, function() {
      console.log('Update 1');
    });

    q.then(() => console.log('Update 2'));
    q.then(() => console.log('Update 3'));
    ```

    Don't mix using callbacks and promises with queries, or you may end up
    with duplicate operations.

    <h3 id="refs"><a href="#refs">References to other documents</a></h3>

    There are no joins in MongoDB but sometimes we still want references to
    documents in other collections. This is where [population](./populate.html)
    comes in. Read more about how to include documents from other collections in
    your query results [here](./api.html#query_Query-populate).

    <h3 id="streaming"><a href="#streaming">Streaming</a></h3>

    You can [stream](http://nodejs.org/api/stream.html) query results from
    MongoDB. You need to call the
    [Query#cursor()](./api.html#query_Query-cursor) function to return an instance of
    [QueryCursor](./api.html#query_Query-cursor).

    ```javascript
    var cursor = Person.find({ occupation: /host/ }).cursor();
    cursor.on('data', function(doc) {
      // Called once for every document
    });
    cursor.on('close', function() {
      // Called when done
    });
    ```

    <h3 id="next"><a href="#next">Next Up</a></h3>

    Now that we've covered `Queries`, let's take a look at [Validation](/docs/validation.html).
